# coding:utf-8
import cv2
import numpy as np
from scipy import misc


class RW(object):
    def __init__(self,img):
        self.im = img
        self.img = self.img_
    @property
    def img_(self):
        # im = cv2.imread(self.im)
        im = misc.imread(self.im)
        return im

    def crop(self):
        gray = cv2.cvtColor(self.img, cv2.COLOR_BGR2GRAY)
        th2 = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 9, 2)
        cv2.imshow('th2',th2)
        binary, contours, hierarchy = cv2.findContours(th2, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
        i = 0
        maxarea = -1
        roci = (0,0,0,0)
        for contour in contours:
            x, y, w, h = cv2.boundingRect(contour)
            if (not abs(h-y) < 5) and not (abs(h-y) > 50):
                tarea = w*h
                if maxarea < tarea:
                    maxarea = tarea
                    roci = (x,y,w,h)
            # print(i)
        cv2.drawContours(self.img,contours,-1,(0,255,0))
        print("矩形宽，高", roci[2], '    ', roci[3])
        img__ = gray[roci[1]:roci[1]+roci[3],roci[0]:roci[0]+roci[2]]
        # cv2.rectangle(self.img, (roci[0], roci[1]), (roci[0] + roci[2], roci[1] + roci[3]), (0, 255, 0), 2)
        img__ = cv2.resize(img__, dsize=(123, 126))
        cv2.imshow('drow',self.img)
        cv2.imshow('croped',img__)
        return img__


    def canny(self):
        img = self.yolo()
        img_g = cv2.GaussianBlur(img, (9,9), 0)
        kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (4,4))
        img_dilate = cv2.dilate(img_g,kernel=kernel)
        canny:np.ndarray = cv2.Canny(img_dilate,0,50)
        # print(np.bincount(canny.flatten()))

        cv2.imshow('canny',canny)





if __name__ == "__main__":
    img = r'C:\Users\Administrator\Desktop\photobase2\THREE\C.jpg'
    img = r'F:\bigphoto\imagu\card\timg.jpg'
    # img = r'C:\Users\Administrator\Desktop\photobase4\TWO\ws5_222_5399.png'
    # img = r'C:\Users\Administrator\Desktop\photobase4\TWO\ws5_2453_3931.png'
    rw = RW(img)
    rw.crop()
    # rw.canny()
    #     #
    #     #
    cv2.waitKey(0)
    cv2.destroyWindow()